package com.lry.jvm.instructions.refrences;

import com.lry.jvm.instructions.base.Index16Instruction;
import com.lry.jvm.rtda.Frame;
import com.lry.jvm.rtda.JObject;
import com.lry.jvm.rtda.OperandStack;
import com.lry.jvm.rtda.heap.ClassRef;
import com.lry.jvm.rtda.heap.JClass;
import com.lry.jvm.rtda.heap.RuntimeConstantPool;

public class jinstanceof extends Index16Instruction {

    @Override
    public byte getOpCode() {
        return (byte) 0xc1;
    }

    @Override
    public void execute(Frame frame) {
        OperandStack stack = frame.getOperandStack();
        JObject ref = stack.popRef();

        //if(obj instanceof Class){}
        //如果obj是null，那么if始终是false
        if(null==ref){
            stack.pushInt(0);
            return;
        }

        RuntimeConstantPool rcp = frame.getMethod().getJClass().getConstantPool();
        ClassRef classRef = (ClassRef) rcp.getConstant(index);
        JClass jClass = classRef.resolvedClass();
        if(ref.isInstanceOf(jClass)){
            stack.pushInt(1);
        }else{
            stack.pushInt(0);
        }
    }
}
